package processus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class ClientReception extends Thread {
    
    protected int pid;
    protected Tampon tampon;

    public ClientReception(Tampon tampon, int pid) {
        this.tampon = tampon;
        this.pid = pid;
    }
    
    @Override
    public void run()
    {
        System.out.println("[ClientReception P"+pid+"] Lancé");
		
		try {
		
			ServerSocket serverSocket = new ServerSocket(6000+pid);
			
            while(true) {
                // On attend une connexion
                Socket socket = serverSocket.accept();
                
                // On lit la ligne
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String cmd = in.readLine();
		        socket.close();
                
                if(cmd == null) {
                    System.err.println("[ClientReception P"+pid+"] Erreur lecture socket");
                }
                else {
                    // Si on doit arréter le client
                    if(cmd.equals("CLOSE")) {
                        break;
                    }

                    // Sinon on dépose le message dans le tampon
                    tampon.deposer(cmd);
                }
            }
            
            serverSocket.close();
		        
		}
        catch (IOException e) {
			e.printStackTrace();
		}
        
        System.out.println("[ClientReception P"+pid+"] Arrété");
    }
    
}